﻿#include "itemedit.h"
#include "ui_itemedit.h"

ItemEdit::ItemEdit(QWidget *parent, const QString &table, bool onlineFlag) :
    BaseEditorDialog(parent),
    _table(table),
    isOnline(onlineFlag),
    ui(new Ui::ItemEdit)
{
    ui->setupUi(this);

    model=new QSqlTableModel(this);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);

    ui->tableView->setModel(model);
    ui->tableView->setEditTriggers(QTableView::DoubleClicked);
    //  ui->tableView->resizeColumnsToContents();

    updateView();
    createMenu();
}

ItemEdit::~ItemEdit()
{
    delete ui;
}

void ItemEdit::updateView()
{
    model->setTable(_table);
    model->select();

    if(!isOnline)
    {
        model->setHeaderData(0,Qt::Horizontal,QStringLiteral("类别"));    //category
        model->setHeaderData(1,Qt::Horizontal,QStringLiteral("名称"));    //label
        model->setHeaderData(2,Qt::Horizontal,QStringLiteral("网址"));    //detail
        ui->tableView->hideColumn(3);       //addition
    }
    else
    {
        ui->tableView->hideColumn(0);   //id
        model->setHeaderData(1,Qt::Horizontal,QStringLiteral("类别"));    //category
        model->setHeaderData(2,Qt::Horizontal,QStringLiteral("名称"));    //label
        model->setHeaderData(3,Qt::Horizontal,QStringLiteral("网址"));    //detail

        //    ui->tableView->setColumnWidth(1,160);
        ui->tableView->setColumnWidth(2,160);
        ui->tableView->hideColumn(4);       //addition
    }
}

void ItemEdit::generateMenu()
{
    menu->addAction(QStringLiteral("撤销"),this,&ItemEdit::revert);
    menu->addAction(QStringLiteral("保存"),this,&ItemEdit::save);
    menu->addSeparator();
    menu->addAction(QStringLiteral("删除"),this,&ItemEdit::removeItem);
}

void ItemEdit::save()
{
    model->submitAll();
    accept();
}

void ItemEdit::removeItem()
{
    if(ui->tableView->currentIndex().isValid())
    {
        int curRow = ui->tableView->currentIndex().row();
        model->removeRow(curRow);
    }
}
